
import TimeObserver from "./TimeObserver";
export default class TimeManager {


    //时间计数
    private totalTime: number = 0;

    private observerList: Array<TimeObserver> = [];

    reset() {
        this.totalTime = 0;
    }


    addTimeListener(observer: TimeObserver) {
        let index = this.has(observer)
        if (index >= 0) {
            return;
        }
        this.observerList.push(observer);
    }

    has(observer: TimeObserver) {
        for (let index = 0; index < this.observerList.length; index++) {
            const element = this.observerList[index];
            if (observer === element) {
                return index;
            }
        }
    }

    removeTimeListener(observer: TimeObserver) {
        let index = this.has(observer)
        if (index >= 0) {
            this.observerList.splice(index, 1);
        }

    }

    getTotalTime() {
        return this.totalTime;
    }

    update(dt: number) {
        // let removes = []
        this.totalTime += dt
        for (let index = 0; index < this.observerList.length; index++) {
            const element: TimeObserver = this.observerList[index];
            // if (totalTime % element.getDuration() == 0) {
            if (element.update(dt)) {
                // if (element.isAutoDelete()) {
                //     removes.push(element)
                // }
            }
        }
        // while (removes.length > 0) {
        //     this.removeTimeListener(removes.shift())
        // }
    }


}
